package problema035;

public class circularPrimes {
	
	static boolean[] isPrime;
	
	public static void main(String[] args){
		System.out.println(cantCircPrimes());
	}
	
	public static int cantCircPrimes(){
		int res = 0;
		sieveOfEratosthenes(1000000);
		for(int i = 0; i < isPrime.length; i++){
			if(isPrime[i] && esCircPrime(i))res++;
		}
		return res;
	}
	
	public static boolean esCircPrime(int i){
		int len = String.valueOf(i).length();
		int[] numero = new int[len];
		int pos = numero.length-1, n = 0, tmp = 0;
		while(i != 0){
			numero[pos] = i % 10;
			i /= 10;
			pos--;
		}
		for(int j = 0; j < numero.length; j++){
			tmp = numero[0];
			for(int k = 0; k < numero.length-1; k++) numero[k] = numero[k+1];
			numero[numero.length-1] = tmp;
			pos = 0; n = 0;
			while(pos < numero.length){
				n += numero[pos] * Math.pow(10, numero.length-pos-1);
				pos++;
			}
			if(!isPrime[n]) return false;
		}
		return true;
	}
	
	public static void sieveOfEratosthenes(int n){
	     isPrime = new boolean[n + 1];
	     for (int i = 2; i <= n; i++) {
	         isPrime[i] = true;
	     }
	     for (int i = 2; i*i <= n; i++) {
	         if (isPrime[i]) {
	             for (int j = i; i*j <= n; j++) {
	                 isPrime[i*j] = false;
	             }
	         }
	     }
	 }

}
